/* -*- c++ -*- */
/*
 * This file is part of the SD Project.
 *
 * Authors: Cleiber Marques da Silva <cleiber@lisha.ufsc.br>
 * 			Odilson Tadeu Valle <odilson@sj.ifsc.edu.br>
 * 
 * SD Project is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; version 2 of the License.
 */

#include <sstream>

#include "delivery.h"

namespace sd {
	delivery::delivery(int size, sd::window *_window)
	{
		messages.resize(size);
		window = _window;
	}

	int delivery::should_send()
	{
		int ok = 1;
	
		mutex.lock();
		for (unsigned int i = 0; i < casual.size(); i++) {
			if (casual[i].id == 1) {
				if (casual[i].seq < 3)
					ok |= 0x1;
				else
					ok &= ~0x1;
			} else if (casual[i].id == 2) {
				if(casual[i].seq >= 6)
					ok |= 0x2;
				else
					ok &= ~0x2;
			} else if (casual[i].id == 3) {
				if (casual[i].seq >= 2)
					ok |= 0x4;
				else
					ok &= ~0x4;
			}
		}
		mutex.unlock();
		return ok;
	}

	void delivery::window_show()
	{	
		struct_message m = casual.back();
		std::ostringstream buffer;
		buffer << "The " << m.id << " said: " << m.mesg;
		buffer << " clock <" << m.timestamp[0] << ", ";
		buffer << m.timestamp[1] << ", " << m.timestamp[2];
		buffer << ">" << std::endl;

		window->fill_buffer(buffer.str());
	}	
}
